package org.nvframe.component.render;

import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateListener;
import org.nvframe.event.eventtype.RenderListener;
import org.nvframe.exception.NVFrameException;
import org.nvframe.manager.ResourceManager;
import org.nvframe.util.settings.SettingsObj;

/**
 * 
 * @author Nik Van Looy
 */
public class RandomImageRender extends ImageRender implements UpdateListener, RenderListener {

	public RandomImageRender(String id, Entity owner, SettingsObj settings) throws NVFrameException {
		super(id, owner, settings);
		
		EventService.getInstance().addEventListener(this);
	}
	
	@Override
	public void loadImage(SettingsObj settings) throws NVFrameException {
		int maxRenderId = 1;
		
		String render = settings.getString("render1", null);
		do {
			maxRenderId++;
			render = settings.getString("render"+maxRenderId, null);
		} while(render != null);
		
		if(render == null)
			maxRenderId--;
		
		int rndRenderId = Math.round((float) (Math.random() * (maxRenderId - 1)) + 1);

		try {
			image = ResourceManager.getInstance().getImage(settings.getString("render" + rndRenderId, null));
		} catch (NVFrameException e) {
			throw new NVFrameException("cannot load image [id:" + rndRenderId + "] for ImageRender component", e);
		}
	}

}